<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" style="width: 60%" scroll :max-height="700">
    <!-- 基本资料 -->
    <div class="title">基本资料</div>
    <ContentWrap>
      <table class="user-info-table">
        <tr>
          <td class="table-label-td">账号</td>
          <td class="table-content-td">{{ formData.mobile }}</td>
          <td class="table-label-td">统一社会信用代码</td>
          <td class="table-content-td">{{ formData.complainCode }}</td>
        </tr>
        <!-- <tr>
          <td class="table-label-td">平台ID</td>
          <td class="table-content-td">{{ formData.platformId }}</td>
        </tr> -->
        <tr>
          <td style="height: 20px"></td>
        </tr>
        <tr>
          <td class="table-label-td">联系地址</td>
          <td class="table-content-td" colspan="3">{{ formData.complainAddress }}</td>
        </tr>
      </table>
    </ContentWrap>
    <!-- 认证状态 -->
    <div class="title">状态</div>
    <ContentWrap>
      <table class="user-info-table">
        <tr>
          <td class="table-label-td">认证状态</td>
          <td class="table-content-td">{{
            getDictLabel(DICT_TYPE.REVIEW_STATUS, formData.reviewStatus)
          }}</td>
          <td class="table-label-td">是否在黑名单</td>
          <td class="table-content-td">{{
            getDictLabel(DICT_TYPE.BACKLIST_STATUS, formData.blacklistStatus)
          }}</td>
        </tr>
      </table>
    </ContentWrap>
    <!-- 认证处理 -->
    <div class="title">认证处理</div>
    <ContentWrap style="padding: 20px">
      <el-button type="info" v-if="formData.reviewStatus == 2">认证已完成</el-button>
      <el-button type="info" v-if="formData.reviewStatus == 0">未认证</el-button>
      <el-button type="info" v-if="formData.reviewStatus == 3">已拒绝</el-button>
      <el-button type="primary" v-if="formData.reviewStatus == 1" @click="openAuditDialog('reject')"
        >驳 回</el-button
      >
      <el-button
        type="primary"
        v-if="formData.reviewStatus == 1"
        @click="openAuditDialog('approve')"
        >通 过</el-button
      >
    </ContentWrap>
    <!-- 组织机构证明材料 -->
    <div class="title">组织机构证明材料</div>
    <ContentWrap> <UploadImg v-model="formData.complainPic" disabled /> </ContentWrap>
    <!-- 子表 -->
    <div class="title">样本订单申请记录</div>
    <ContentWrap>
      <el-table :data="orderList" :stripe="true" :show-overflow-tooltip="true">
        <el-table-column label="订单编号" align="center" prop="orderNo" />
        <el-table-column
          label="提交时间"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
          width="180px"
        />
        <!--        <el-table-column label="用户账号" align="center" prop="userPhone" />-->
        <el-table-column label="样本订单状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.JK_ORDER_STATUS" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" min-width="120px" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="detailHandler('', scope.row.id)">
              订单详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </ContentWrap>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <!-- 统一审核弹窗 -->
  <Dialog title="输入审批意见" v-model="auditDialogVisible" style="min-width: 500px">
    <el-form-item label="审批意见" prop="opinion">
      <el-input
        type="textarea"
        v-model="reviewOpinion"
        placeholder="请输入审批意见..."
        maxlength="300"
        show-word-limit
        rows="4"
      />
    </el-form-item>
    <template #footer>
      <el-button @click="auditDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="confirmAudit">{{ confirmButtonText }}</el-button>
    </template>
  </Dialog>

  <!-- 子表详情 -->
  <OrderDetailForm ref="ChildformRef" />
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE, getDictLabel } from '@/utils/dict'
import { UserApi, UserVO } from '@/api/jikong/out-user'
import { JkOrderApi, JkOrderVO } from '@/api/jikong/jkOrder'
import { ref, reactive } from 'vue'
import OrderDetailForm from './orderDetailForm.vue'

defineOptions({ name: 'OrgUserForm' })

const { t } = useI18n()
const message = useMessage()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const formData = ref({
  id: undefined,
  userType: 1, // 机构用户，userType 设为 1
  name: undefined,
  password: undefined,
  mobile: undefined,
  userAddress: undefined,
  complainName: undefined,
  complainCode: undefined,
  platformId: undefined,
  complainPic: undefined,
  complainAddress: undefined,
  realName: undefined,
  realNo: undefined,
  realPicPerson: undefined,
  realPicBack: undefined,
  realPicHolding: undefined,
  status: undefined,
  blacklistStatus: undefined,
  reviewStatus: undefined
})
const formRules = reactive({
  // mobile: [{ required: true, message: '账号不能为空', trigger: 'blur' }],
  // complainCode: [{ required: true, message: '机构代码不能为空', trigger: 'blur' }],
  // platformId: [{ required: true, message: '平台ID不能为空', trigger: 'blur' }],
  // complainAddress: [{ required: true, message: '联系地址不能为空', trigger: 'blur' }]
})
const formRef = ref()

// 审核弹窗相关变量
const auditDialogVisible = ref(false)
const auditType = ref<'approve' | 'reject'>('approve')
const reviewOpinion = ref('')
const confirmButtonText = ref('')

/** 打开审核弹窗 */
const openAuditDialog = (type: 'approve' | 'reject') => {
  auditType.value = type
  reviewOpinion.value = ''

  if (type === 'approve') {
    confirmButtonText.value = '确认通过'
  } else {
    confirmButtonText.value = '确认驳回'
  }

  auditDialogVisible.value = true
}

/** 确认审核操作 */
const confirmAudit = async () => {
  try {
    const reviewStatus = auditType.value === 'approve' ? 2 : 3
    await UserApi.updateReviewStatus({
      id: formData.value.id,
      reviewStatus,
      passWords: auditType.value === 'approve' ? reviewOpinion.value : '',
      rejectWords: auditType.value !== 'approve' ? reviewOpinion.value : ''
    })
    auditDialogVisible.value = false
    await refreshUserInfo()
  } catch (error) {}
}
/** 打开表单弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  if (id) {
    formLoading.value = true
    try {
      formData.value = await UserApi.getUser(id)
      getOrderList(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open })

/** 提交表单 */
const emit = defineEmits(['success'])
const submitForm = async () => {
  // await formRef.value.validate()
  formLoading.value = true
  try {
    const data = formData.value as unknown as UserVO
    if (formType.value === 'create') {
      await UserApi.createUser(data)
      message.success(t('common.createSuccess'))
    } else {
      await UserApi.updateUser(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 刷新用户信息 */
const refreshUserInfo = async () => {
  if (formData.value.id) {
    formLoading.value = true
    try {
      formData.value = await UserApi.getUser(formData.value.id)
    } finally {
      formLoading.value = false
    }
  }
}

/** 获取个人申请信息 */
const orderList = ref([])
const getOrderList = async (id) => {
  try {
    const data = await JkOrderApi.getUserOrderPage({ userId: id })
    orderList.value = data.list
  } catch (error) {}
}

/** 查看子表详情 */
const ChildformRef = ref()
const detailHandler = (type: string, id?: number) => {
  ChildformRef.value.open(type, id)
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    userType: 1,
    name: undefined,
    password: undefined,
    mobile: undefined,
    userAddress: undefined,
    complainName: undefined,
    complainCode: undefined,
    platformId: undefined,
    complainPic: undefined,
    complainAddress: undefined,
    realName: undefined,
    realNo: undefined,
    realPicPerson: undefined,
    realPicBack: undefined,
    realPicHolding: undefined,
    status: undefined,
    blacklistStatus: undefined,
    reviewStatus: undefined
  }
  formRef.value?.resetFields()
}
</script>
<style scoped>
.title {
  margin: 5px 0;
  font-weight: 500;
}
/* 基础信息表格：消除 td 间隔 + 统一边框 */
.user-info-table {
  width: 100%; /* 表格占满容器宽度 */
  border-collapse: collapse; /* 关键：合并单元格边框，消除间隔 */
}

/* 表格标题列：灰色背景、固定宽度、右对齐 */
.table-label-td {
  width: 130px;
  padding: 10px;
  text-align: right;
  background-color: #f9fafc;
  border: 1px solid #e4e7ed; /* 统一边框样式 */
}

/* 表格内容列：固定宽度、左对齐 */
.table-content-td {
  width: 200px;
  padding: 10px;
  border: 1px solid #e4e7ed; /* 统一边框样式，与标题列一致 */
}

/* 修复 el-form 中 flex 布局的换行问题（可选优化） */
.el-form .flex {
  display: flex;
  gap: 24px; /* 表单项之间的间距 */
  margin-bottom: 16px;
  flex-wrap: wrap; /* 自适应换行 */
}
</style>
